package com.example.activity;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.adapter.CityListAdapter;
import com.example.consts.City;
import com.example.consts.Consts;
import com.example.dianping.R;
import com.example.entity.ResponseObject;
import com.example.utils.ToastMaker;
import com.example.view.SideBar;
import com.example.view.SideBar.OnTouchingLetterChangedListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

public class CityActivity extends Activity implements
		OnTouchingLetterChangedListener {

	@ViewInject(R.id.city_list)
	private ListView city_list;
	private List<City> cityListdats;
	@ViewInject(R.id.side_bar)
	private SideBar sideBar;

	private TextView dialogText;
	private WindowManager windowManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_layout);
		ViewUtils.inject(this);

		View view = LayoutInflater.from(this).inflate(
				R.layout.home_city_search, null);

		new CityDataTask().execute();
		city_list.addHeaderView(view);

		sideBar.setOnTouchingLetterChangedListener(this);

		dialogText = (TextView) LayoutInflater.from(this).inflate(
				R.layout.city_select_remind, null);
		dialogText.setVisibility(View.INVISIBLE);

		windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
						| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		windowManager.addView(dialogText, lp);

		sideBar.setTextView(dialogText);

	}

	@OnItemClick(R.id.city_list)
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent = new Intent();
		TextView textView = (TextView) view
				.findViewById(R.id.tv_city_list_item_name);
		intent.putExtra("cityName", textView.getText().toString());
		setResult(RESULT_OK, intent);
		finish();
	}

	// ���ذ�ť�ĵ���¼�
	@OnClick({ R.id.city_back, R.id.city_refresh })
	private void OnClick(View view) {
		switch (view.getId()) {
		case R.id.city_back:
			finish();
			break;
		case R.id.city_refresh:
			new CityDataTask().execute();

			break;
		default:
			break;
		}
	}

	// ʹ���첽�����ȡ����JSon

	public class CityDataTask extends AsyncTask<Void, Void, List<City>> {

		@Override
		protected List<City> doInBackground(Void... params) {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.City_Data_URI);

			try {
				HttpResponse httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {

					String jsonString = EntityUtils.toString(httpResponse
							.getEntity());
					return parseCityDatasJson(jsonString);

				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<City> result) {
			super.onPostExecute(result);
			cityListdats = result;
			// ������ʾ
			CityListAdapter cityListAdapter = new CityListAdapter(
					CityActivity.this, cityListdats);
			city_list.setAdapter(cityListAdapter);

		}

	}

	// �������ص�json�ַ�
	private List<City> parseCityDatasJson(String string) {
		Gson gson = new Gson();
		ResponseObject<List<City>> responseObject = gson.fromJson(string,
				new TypeToken<ResponseObject<List<City>>>() {
				}.getType());

		return responseObject.getDatas();
	}

	@Override
	public void onTouchingLetterChanged(String s) {
		city_list.setSelection(findIndex(cityListdats, s));

	}

	private int findIndex(List<City> list, String s) {
		if (list != null) {
			for (int i = 0; i < cityListdats.size(); i++) {
				if (s.equals(cityListdats.get(i).getSortKey())) {
					// 由于索引位置最前边有个定位项，所以占用一格，
					// 要让点击索引正好显示所选字母处，要用i+1
					return i + 1;
				}
			}
		} else {
			ToastMaker.showLongToast("暂无信息");
		}
		return -1;
	}

}
